<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑报告所属人"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <!-- 搜索输入框 -->
    <div class="search-input-wrapper">
      <el-input
        v-model="searchName"
        placeholder="请输入姓名"
        clearable
        @keyup.enter="handleSearch(searchName)"
      />
      <el-button
        type="primary"
        :loading="searching"
        :disabled="!searchName.trim()"
        @click="handleSearch(searchName)"
      >
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
    </div>

    <!-- 用户列表表格 -->
    <el-table
      v-if="userList.length > 0"
      :data="userList"
      style="width: 100%; margin-top: 20px"
      max-height="300px"
      @row-click="handleRowClick"
    >
      <el-table-column width="55">
        <template #default="{ row }">
          <el-radio
            v-model="selectedUserId"
            :label="row.userId"
            @change="handleUserSelect(row)"
          >
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="actualName" label="姓名" />
      <!-- 可以根据需要添加更多列 -->
      <el-table-column v-if="userList[0]?.phone" prop="phone" label="手机号" />
      <el-table-column v-if="userList[0]?.email" prop="email" label="邮箱" />
    </el-table>

    <!-- 无数据提示 -->
    <!-- <div
      v-if="searchName && userList.length === 0 && !searching"
      class="no-data"
    >
      <el-empty description="未找到匹配的用户" />
    </div> -->

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          :disabled="!selectedUser"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { addReportApi } from "@/api/addReport";
import { getUserInfoByUserName } from "@/api/user";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { ref } from "vue";

interface Props {
  reportId?: number;
  currentName?: string;
}

interface UserInfo {
  userId: number;
  actualName: string;
  phone?: string;
  email?: string;
  // 可以根据实际接口返回添加更多字段
}

const props = withDefaults(defineProps<Props>(), {
  reportId: undefined,
  currentName: ""
});

const emit = defineEmits<{
  (e: "update", data: { reportId?: number; name: string }): void;
  (e: "close"): void;
}>();

const dialogVisible = ref(false);
const loading = ref(false);
const searching = ref(false);
const searchName = ref("");
const userList = ref<UserInfo[]>([]);
const selectedUser = ref<UserInfo | null>(null);
const selectedUserId = ref<number | null>(null);

// 打开弹窗
const open = (name?: string) => {
  searchName.value = name || "";
  userList.value = [];
  selectedUser.value = null;
  selectedUserId.value = null;
  dialogVisible.value = true;
  // 如果有初始名字，自动查询用户信息
  if (name) {
    handleSearch(name);
  }
};

// 关闭弹窗
const handleClose = () => {
  searchName.value = "";
  userList.value = [];
  selectedUser.value = null;
  selectedUserId.value = null;
  dialogVisible.value = false;
  emit("close");
};

// 执行搜索
const handleSearch = async (value: string) => {
  if (!value.trim()) {
    ElMessage.warning("请输入姓名");
    return;
  }

  searching.value = true;
  try {
    const res = await getUserInfoByUserName({ userName: value.trim() });
    if (res.code === 0 && res.data.length > 0) {
      userList.value = res.data;
      // 清空之前的选择
      selectedUser.value = null;
      selectedUserId.value = null;
    } else {
      userList.value = [];
      ElMessage.warning("未找到用户信息");
    }
  } catch (error) {
    console.error("查询用户信息失败:", error);
    ElMessage.error("查询用户信息失败");
    userList.value = [];
  } finally {
    searching.value = false;
  }
};

// 处理用户选择
const handleUserSelect = (user: UserInfo) => {
  selectedUser.value = user;
  selectedUserId.value = user.userId;
};

// 处理表格行点击
const handleRowClick = (row: UserInfo) => {
  selectedUserId.value = row.userId;
  handleUserSelect(row);
};

// 确认更新
const handleConfirm = async () => {
  if (!searchName.value.trim()) {
    ElMessage.warning("请输入姓名");
    return;
  }

  if (!selectedUser.value) {
    ElMessage.warning("请选择一个用户");
    return;
  }

  if (!props.reportId) {
    ElMessage.warning("报告ID不能为空");
    return;
  }

  loading.value = true;
  try {
    const res = await addReportApi.reportBindUserId({
      bindUserId: selectedUser.value.userId,
      reportId: props.reportId
    });

    if (res.code === 0) {
      emit("update", {
        reportId: props.reportId,
        name: selectedUser.value.actualName
      });
      handleClose();
    } else {
      ElMessage.error(res.data?.message || "绑定失败");
    }
  } catch (error) {
    console.error("绑定用户失败:", error);
    ElMessage.error("绑定用户失败");
  } finally {
    loading.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.search-input-wrapper {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;

  .el-input {
    flex: 1;
  }

  .el-button {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.no-data {
  margin-top: 20px;
  text-align: center;
}

// 表格行点击样式
:deep(.el-table__row) {
  cursor: pointer;

  &:hover {
    background-color: #f5f7fa;
  }
}

// 单选按钮样式调整
:deep(.el-radio) {
  .el-radio__label {
    display: none;
  }
}
</style>
